package com.program.facesigninsystem.config;

import com.auth0.jwt.JWT;
import com.program.facesigninsystem.entity.ResponseModel;
import com.program.facesigninsystem.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;
//import java.util.logging.Level;
//import java.util.logging.Logger;

/**
 * @author Mapler
 */
@Slf4j
public class ReqInterceptor extends HandlerInterceptorAdapter {
    //    private static Logger log = Logger.getLogger(ReqInterceptor.class.toString());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //得到请求头
        if ("OPTIONS".equals(request.getMethod())) {
            //在拦截器中设置允许跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "3600");
            return true;
        }

        //获得token
        String authorization = request.getHeader("Authorization");
        String token = null;
        if (authorization != null) {
            token = authorization.substring(7);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //如果token没有则返回
        if (token == null || token.length() == 0) {
            JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "无token，不允许访问！").toString());
            response.getWriter().append(jsonObject.toString()).flush();
            return false;
        } else {
            try {
                Long currentTime = System.currentTimeMillis();
                Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
                Long expTime = JWT.decode(token).getClaim("exptime").asLong();
                if (currentTime - generateTime > expTime) {
                    JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "token过期，请重新登录！").toString());
                    response.getWriter().append(jsonObject.toString()).flush();
                    return false;
                }

                //权限验证
                String uri = request.getRequestURI();
                log.info("URI:" + uri);
                if (uri.matches("/authority/getAuthApplyHistory")
                        || uri.matches("/authority/getGroupList")
                        || uri.matches("/authority/getOneAuthApplyDetail")
                        || uri.matches("/authority/getOwnAuth")
                        || uri.matches("/authority/subAuthApply")
                        || uri.matches("/teacher/.*")) {
                    int role = TokenUtil.decodeTokenGetRole(token);
                    if (role == 0) {
                        JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "权限不足！").toString());
                        response.getWriter().append(jsonObject.toString()).flush();
                        return false;
                    }
                }

            } catch (Exception e) {
//                    log.log(Level.SEVERE,"Error parsing date",e);
                log.info(e.getMessage());
                //验证失败
                JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "token无效，不允许访问！").toString());
                response.getWriter().append(jsonObject.toString()).flush();
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }
}
